package com.xymtop.sqlcater.core.sql.sqlparser.tosql.utils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class CaterFileUtil {

    //一行一行的读取文件

    public static List readFileLine(String path) throws IOException {
        FileInputStream fis=new FileInputStream(path);
        InputStreamReader isr=new InputStreamReader(fis, "UTF-8");
        BufferedReader br = new BufferedReader(isr);
        //简写如下
        String line="";
        List<String> content = new ArrayList<>();
        while ((line=br.readLine())!=null) {
           content.add(line);
        }
        br.close();
        isr.close();
        fis.close();

        return content;
    }


    public static  void writeFileLine(List<String> content,String path) throws IOException {

        //写入中文字符时解决中文乱码问题
        FileOutputStream fos=new FileOutputStream(new File(path));
        OutputStreamWriter osw=new OutputStreamWriter(fos, "UTF-8");
        BufferedWriter  bw=new BufferedWriter(osw);
        //简写如下：
        //BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
        //        new FileOutputStream(new File("E:/phsftp/evdokey/evdokey_201103221556.txt")), "UTF-8"));

        for(String arr:content){
            bw.write(arr+"\t\n");
        }

        //注意关闭的先后顺序，先打开的后关闭，后打开的先关闭
        bw.close();
        osw.close();
        fos.close();
    }


    public static void write(String str,String path) throws IOException {
        List<String> list = new ArrayList<>();

        list.add(str);
        writeFileLine(list,path);

    }


    public static  void writeStr(String data,String path){

        try{
            File file = new File(path);
            if(!file.exists()){

                //判断目录是否存在
                File dir = file.getParentFile();
                if(!dir.exists()){
                    dir.mkdir();
                }

                file.createNewFile();
            }
            FileWriter fileWritter = new FileWriter(file.getAbsoluteFile(),false);
            fileWritter.write(data);
            fileWritter.close();
        }catch(IOException e){
            e.printStackTrace();
        }
    }

}
